package zjh.msg.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        // 加载配置文件
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatisConfig.xml");
            if (inputStream == null) {
                throw new RuntimeException("找不到 mybatisConfig.xml 文件");
            }
            // 创建工厂类
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            System.out.println("Mybatis 初始化成功！");
        } catch (IOException e) {
            throw new RuntimeException("初始化 MybatisUtil 失败", e);
        }
    }

    public static SqlSession getSqlSession() {
//        SqlSessionFactory sqlSessionFactory = null;
        return sqlSessionFactory.openSession();
    }
}
